import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_member_mvvm/routes/navigator_util.dart';
import 'package:flutter_member_mvvm/util/Counter.dart';
import 'package:flutter_member_mvvm/util/over_scroll_behavior.dart';

import 'package:flutter_model_package/Member.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:package_info/package_info.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';
import 'package:provide/provide.dart';
import 'package:sort_price/sort_price.dart';

class PersonalCenterScreen extends StatefulWidget {
  @override
  _PersonalCenterScreenState createState() => _PersonalCenterScreenState();
}

class _PersonalCenterScreenState extends State<PersonalCenterScreen> {
  ParseUser user;

//  會員對象
  var member = Member();

//  app版本信息
  String appNameVersion = "Unknown";

  /// 获得会员信息
  Future<void> getMemberInfo() async {
    final ParseUser user = await ParseUser.currentUser() as ParseUser;
    if(user!=null){
      var querymember = QueryBuilder<ParseObject>(ParseObject('_User'))
        ..whereEqualTo('objectId', user.objectId)
        ..includeObject(['member']);
      var rep = await querymember.query();
      if (rep.statusCode == 200 && rep.results != null) {
        setState(() {
          member = rep.results.first['member'];
          print(member);
        });
      }
    }
  }

  Future<void> initUser() async {
    user = await ParseUser.currentUser();
  }

  //  獲得app版本號信息
  Future<void> getAppInfo() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    setState(() {
      appNameVersion = packageInfo.appName + packageInfo.version;
    });
  }
  @override
  void initState() {
    super.initState();
    getAppInfo();
    initUser();
    getMemberInfo();
  }

  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0, //取消頂部陰影
        automaticallyImplyLeading: false, //取消默認返回箭頭
      ),
      body: ScrollConfiguration(
          behavior: OverScrollBehavior(),
          child: Container(
            child: Column(
              children: <Widget>[
                //頭像
                _headWidget(
                    netImg: member.get("avatar") != null
                        ? member.get("avatar")['url']
                        : "undefined",
                    userName: member.get("displayName"),
                onTop: ()=>NavigatorUtil.jump(context, user==null?"/login":"/editmemInfo/${user.get("member")["objectId"]}")),
                //積分/餘額
                Container(
                  padding: EdgeInsets.only(top: ScreenUtil().setHeight(20)),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      ItemColumn(
                          title: member.get('credit') != null
                              ? sortPrice(member.get('credit')).toString()
                              : '0',
                          // title: sortPrice(100000),
                          description: '積分',
                          onTop: () => NavigatorUtil.jump(context,
                              "/membershippage/${member.get('credit')}")),
                      //餘額
                      SplitLine(),
                      ItemColumn(
                          title: member.get('balance') != null
                              ? "\$${sortPrice(member.get('balance'))}"
                                  .toString()
                              : '\$ 0',
                          description: '餘額',
                          onTop: () => NavigatorUtil.jumpLoginState(context,title: "/balance/${sortPrice(member.get('balance'))}")),
                    ],
                  ),
                ),
                //設置選項
                Center(
                  child: Container(
                    width: ScreenUtil().setWidth(187),
                    padding: EdgeInsets.only(top: ScreenUtil().setHeight(20)),
                    child: Provide<Counter>(
                      builder: (BuildContext context,child,counter){
                        return Column(
                          children: <Widget>[
                            setting(
                                title: '我的課程',
                                src: 'assets/drawer/my_course.png',
                                onTop: () => NavigatorUtil.jump(context,
                                    user != null ? '/myCourse' : '/login')),
                            setting(
                                title: '訂單紀錄',
                                src: 'assets/drawer/order.png',
                                onTop: () => NavigatorUtil.jump(
                                    context,
                                    user != null
                                        ? '/index/subpage/order/${counter.stuId}'
                                        : '/login')),
                            setting(
                                title: '聯絡我們',
                                src: 'assets/drawer/service.png',
                                onTop: () =>
                                    NavigatorUtil.jump(context, '/indexChat')),
                            setting(
                                title: '設置',
                                src: 'assets/drawer/settings.png',
                                onTop: () =>
                                    NavigatorUtil.jump(context, "/settings")),
                            setting(
                                title: '檢查更新',
                                src: 'assets/drawer/update.png',
                                onTop: () async {
                                  try{
                                    final channel = const MethodChannel("com.macauscholar.app/update");
                                    await channel.invokeMethod("VersoinUpdate");
                                  }catch (e){
                                    print(e);
                                  }
                                }),
                          ],
                        );
                      },
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    alignment: Alignment.bottomCenter,
                    margin: EdgeInsets.only(bottom: 20),
                    child: Text(
                      "$appNameVersion",
                      style: TextStyle(
                          color: Color(0xff8D92A6),
                          fontSize: ScreenUtil().setSp(13),
                          fontFamily: "SemiBold"),
                    ),
                  ),
                )
              ],
            ),
          )),
    );
  }

  ///  積分和餘額上下分佈Item
  Widget ItemColumn(
      {@required String title,
      @required String description,
      VoidCallback onTop}) {
    return InkWell(
      onTap: onTop,
      child: Container(
        width: ScreenUtil().setWidth(120),
        child: GestureDetector(
          onTap: onTop,
          child: Column(
            children: <Widget>[
              Container(
                child: Text(
                  title,
                  style: TextStyle(
                      fontSize: ScreenUtil().setSp(21),
                      color: Color(0Xff154D7C),
                      fontWeight: FontWeight.bold),
                ),
              ),
              Container(
                child: Text(
                  description,
                  style: TextStyle(
                      fontSize: ScreenUtil().setSp(12),
                      color: Color(0Xff7897B2),
                      fontWeight: FontWeight.bold),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  ///頭像
  Widget _headWidget({String netImg, String src, String userName,VoidCallback onTop}) {
    return Container(
      width: ScreenUtil().setWidth(197),
      child: GestureDetector(
        child: Container(
          child: Column(
            children: <Widget>[
              Container(
                height: 55,
                width: 55,
                child: netImg != "undefined"
                    ? CircleAvatar(
                        backgroundImage: NetworkImage(netImg),
                        radius: 55,
                      )
                    : CircleAvatar(
                        backgroundColor: Colors.transparent,
                        backgroundImage: AssetImage('images/avatar.png'),
                        radius: 55,
                      ),
              ),
              Container(
                padding: EdgeInsets.fromLTRB(0, 10, 0, 0),
                child: Text(
                  userName != null ? userName : '用戶名稱',
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(14),
                    color: Color(0Xff2D7FC7),
                    fontFamily: "SemiBold",
                  ),
                ),
              ),
            ],
          ),
        ),
        onTap:onTop,
      ),
    );
  }

  //  分割線
  Widget SplitLine() {
    return Container(
        width: 1,
        height: ScreenUtil().setHeight(44),
        decoration: BoxDecoration(
          border: Border(
            right: BorderSide(
                color: Color(0Xff7897B2), width: 1, style: BorderStyle.solid),
          ),
        ));
  }

// 設置組件
  Widget setting({String title, String src, VoidCallback onTop}) {
    return InkWell(
      child: Row(
        children: <Widget>[
          Container(
            margin: EdgeInsets.all(12),
            child: Image.asset(
              src,
              width: 20,
              height: 20,
            ),
          ),
          Text(
            title,
            style: TextStyle(
              fontSize: ScreenUtil().setSp(14),
              color: Color(0Xff154D7C),
              fontWeight: FontWeight.bold,
              fontFamily: "SemiBold",
            ),
          ),
        ],
      ),
      onTap: onTop,
    );
  }
}
